/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logbook.ui;

import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;

public class LogsTableModel extends AbstractTableModel {

  private Statement stmt;
  private String[] columnNames = {"Id", "Date", "Notes"};
  private List<List> data = new ArrayList<List>();

  public LogsTableModel(Statement stmt) {
    this.stmt = stmt;
  }

  public void refreshData(String key) {
    data.clear();

    ResultSet rs = null;
    try {
      rs = stmt.executeQuery("select a.id, a.entry_date, a.notes "
              + "from entry a, keys b where a.kid = b.id "
              + "and b.key = '" + key.replace("'", "''") + "'");
      while (rs.next()) {
        List l = new ArrayList();
        l.add(rs.getString(1));
        l.add(rs.getString(2));
        l.add(rs.getString(3));

        data.add(l);
      }

      this.fireTableDataChanged();
    } catch (Exception e) {
      e.printStackTrace(System.err);
    } finally {
      try {
        rs.close();
      } catch (Exception x) {
      }
    }
  }

  @Override
  public int getColumnCount() {
    return columnNames.length;
  }

  @Override
  public int getRowCount() {
    return data.size();
  }

  @Override
  public String getColumnName(int col) {
    return columnNames[col];
  }

  @Override
  public Object getValueAt(int row, int col) {
    return data.get(row).get(col);
  }

  @Override
  public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
  }

  /*
   * Don't need to implement this method unless your table's editable.
   */
  @Override
  public boolean isCellEditable(int row, int col) {
    return false;
  }

  /*
   * Don't need to implement this method unless your table's data can change.
   */
  @Override
  public void setValueAt(Object value, int row, int col) {
    data.get(row).set(col, value);
    fireTableCellUpdated(row, col);
  }
}
